import React, { Component } from 'react';
import Input from './input'
import Things from './things'
import ToolBar from './toolbar.jsx'
export default class ToDoList extends Component {
    constructor(data) {
        super(data)
        this.state = {
            ThingsList: []
        }
        this.input=React.createRef()
    }
    onEnter(e){
        let temp=this.state.ThingsList.slice()
        temp.push(e.target.value)
        if(e.keyCode==13){
           this.setState({
               ThingsList:temp
           },()=>{
            this.input.current.ClearInput()
           })
        }
    }
    delThing(e,index){
        console.log(e,index);
        let temp=this.state.ThingsList.slice()
        for(var i in temp){
            if(i==index){
                temp.splice(index,1) 
                break
            }
        }
        this.setState({
            ThingsList:temp
        })
    }
    render() {
        return (
            <div className="todolist-body">
                <Input 
                    ref={this.input}
                    onEnter={this.onEnter.bind(this)}
                />
                <div className='things-body'>
                    {
                        this.state.ThingsList.map((item,index)=>{
                            return   < Things
                                key={index}
                                name={item}
                                delThing={this.delThing.bind(this)}
                                index={index}
                            />
                        })
                    }
                </div>
                <ToolBar
                    ThingLen={this.state.ThingsList.length}
                />
            </div>
        )
    }
}